const Koa = require('koa');
const KoaStatic = require('koa-static');
const KoaBody = require('koa-body');
const KoaSession = require('koa-session');

const { port, staticDir } = require('./config');
const static = require('./src/middleware/static')

const app = new Koa();

// 异常处理中间件

// // 静态资源请求重写url
const rewriteUrl = require('./src/middleware/rewriteUrl');
app.use(rewriteUrl);

// // koa-static处理静态资源
// app.use(KoaStatic(staticDir));
app.use(KoaStatic(__dirname + '/public'));

// 处理session
const CONFIG = require('./src/middleware/session')
app.keys = ['session app keys'];
app.use(KoaSession(CONFIG, app))

// app.use(async (ctx, next) => {
//     ctx.state.user = ctx.session.user;
//     await next();
// });

// 判断是否登录
const isLogin = require('./src/middleware/isLogin');
app.use(isLogin);
// 处理请求体数据
const koaBodyConfig = require('./src/middleware/koaBodyConfig');
app.use(KoaBody(koaBodyConfig));


// 处理路由中间件
const Routers = require('./src/routers');
// 调用router的routes方法获取到对应的koa中间件，调用了 allowedMethods 方法注册了 HTTP 方法检测的中间件，这样当用户通过不正确的 HTTP 方法访问 API 时，就会自动返回 405 Method Not Allowed 状态码
app.use(Routers.routes()).use(Routers.allowedMethods());

app.listen(port, () => {
    console.log(`私服启动${port}端口`);
})